const Answer = require('../models/answers')

class AnswerCtl {
  /**
   * 查找答案列表
   * (传入问题 ID)
   * @param {Object} ctx 
   */
  async find(ctx) {
    const { per_page = 3 } = ctx.query
    const page = Math.max(ctx.query.page * 1, 1) - 1
    const perPage = Math.max(per_page * 1, 1)
    const q = new RegExp(ctx.query.q)
    ctx.body = await Answer
      .find({ content: q, questionId: ctx.params.questionId })
      .limit(perPage).skip(page * perPage)
  }
  /**
   * 检查答案是否存在
   * @param { Object} ctx 
   * @param { Object} next 
   */
  async checkAnswerExist(ctx, next) {
    const answer = await Answer.findById(ctx.params.id).select('+answerer')
    if (!answer) {
      ctx.throw(404, '答案不存在')
    }
    if (ctx.params.questionId && answer.questionId !== ctx.params.questionId) {
      ctx.throw(404, '该问题下没有此答案')
    }
    ctx.state.answer = answer
    await next()
  }
  /**
   * 查找特定的答案
   * @param {Object} ctx 
   */
  async findById(ctx) {
    const { filelds = '' } = ctx.query
    const selectFields = filelds.split(';').filter(f => f).map(f => ' +' + f).join('')
    const answer = await Answer.findById(ctx.params.id).select(selectFields).populate('answerer')
    ctx.body = answer
  }
  /**
   * 创建答案
   * @param {Object} ctx 
   */
  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true }
    })
    const answerer = ctx.state.user._id
    const { questionId } = ctx.params
    const answer = await new Answer({ ...ctx.request.body, answerer, questionId }).save()
    ctx.body = answer
  }
  /**
   * 检查该用户是否是该答案的创建者
   * @param {Object} ctx 
   * @param {Object} next 
   */
  async checkAnswerer(ctx, next) {
    const { answer } = ctx.state
    console.log(ctx.answer)
    if (answer.answerer.toString() !== ctx.state.user._id) {
      ctx.throw(403, '没有更改权限')
    }
    await next()
  }
  /**
   * 修改答案
   * @param {Object} ctx 
   */
  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false }
    })
    await ctx.state.answer.update(ctx.request.body)
    ctx.body = ctx.state.answer
  }
  /**
   * 删除答案
   * @param {Object} ctx 
   */
  async delete(ctx) {
    await Answer.findByIdAndRemove(ctx.params.id)
    ctx.status = 204
  }
}

module.exports = new AnswerCtl()